<script setup name="ZlAgency">
import Message from 'vue-m-message'
import { ElMessageBox } from 'element-plus'
import zlAgencyService from '@/api/finance/zlAgency.js'
import BaseForm from '@/components/BaseForm/BaseForm.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { formatDate } from '@/utils/dayjs.js'
import { useDict } from '@/utils/dict.js'

const tableData = ref([])
const customerName = ref([])
const queryParam = ref({
  status: '0',
})
const ids = ref([])
const btnLoad = ref(false)
const updateDialogVisible = ref(false)
const updateDialogTitle = ref('修改备注')
const customerlist = ref([])
const formDisabled = ref(false)
const { proxy } = getCurrentInstance()
const { sys_proceeds_time, sys_pay_status } = useDict('sys_proceeds_time', 'sys_pay_status')

const searchConfig = reactive([
  {
    label: '合同编号',
    field: 'contractNo',
    type: 'input',
    defaultShow: true,
  },
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerlist,
      label: 'customerName',
      value: 'customerId',
      key: 'customerId',
    },
  }, {
    label: '案件编号',
    field: 'reelNumber',
    type: 'input',
    defaultShow: true,
  }, {
    label: '案件名称',
    field: 'patentName',
    type: 'input',
    defaultShow: true,
  }, {
    label: '业务类型',
    field: 'patentType',
    type: 'input',
  },
  {
    label: '收款节点',
    field: 'skNode',
    type: 'select',
    options: {
      data: sys_proceeds_time,
      label: 'label',
      value: 'value',
      key: 'value',
    },
  },
  {
    label: '备注',
    field: 'remark',
    type: 'input',
  },

])

const tableColumns = reactive([
  { type: 'checkbox', width: 50 },
  { type: 'seq', width: 50 },
  {
    field: 'customerName',
    title: '客户名称',
    align: 'center',
    minWidth: 200,
    // slots: { default: ({ row }) => {
    //   return h(ElLink, {
    //     type: 'primary',
    //     onClick : () => {
    //       router.push({ path: '/customerInformation', query: { customerId: row.customerId } })
    //     },
    //   }, { default: () => row.customerName })
    // } },
  },
  {
    field: 'contractNo',
    title: '合同编号',
    align: 'center',
    minWidth: 140,
    showOverflow: 'tooltip',
  },
  {
    field: 'reelNumber',
    title: '案件编号',
    align: 'center',
    minWidth: 140,
    showOverflow: 'tooltip',
  },
  {
    field: 'patentName',
    title: '案件名称',
    align: 'center',
    minWidth: 220,
    showOverflow: 'tooltip',

  },
  {
    field: 'businessName',
    title: '业务名称',
    align: 'center',
    minWidth: 120,
  },
  {
    field: 'skNode',
    title: '收款节点',
    align: 'center',
    minWidth: 80,
    slots: { default: 'skNode' },
  },
  {
    field: 'dsMoney',
    title: '待收费用',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'dlMoney',
    title: '代理费',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'gfMoney',
    title: '官费',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'otherMoney',
    title: '其他费用',
    align: 'center',
    minWidth: 100,
    showOverflow: 'tooltip',
  },
  {
    field: 'status',
    title: '状态',
    align: 'center',
    minWidth: 80,
    showOverflow: 'tooltip',
    slots: { default: 'status' },
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 150,
    fixed: 'right',
    slots: { default: 'operate' },
  }])

const updateFormList = ref([
  {
    label: '备注',
    field: 'remark',
    type: 'textarea',
    span: 24,
  },
])
const updateFormModel = ref({})

const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

onMounted(() => {
  getList()
})

function getList() {
  const formData = {
    ...queryParam.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
    status: 0,
  }
  btnLoad.value = true
  zlAgencyService.list(formData).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    btnLoad.value = false
  })
  zlAgencyService.optionList().then((res) => {
    customerlist.value = res.data
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange({ checked, records, reserves }) {
  const res = records.map(item => item.customerId)
  if (reserves.length > 0) {
    if (checked) {
      ids.value.push(...res)
    }
    else {
      const customerIdSet = new Set(reserves.map(item => item.customerId))
      ids.value = ids.value.filter(item => customerIdSet.has(item))
    }
  }
  else {
    ids.value = res
  }
}

function handleSearch(e, type) {
  if (type === 'reset') {
    customerName.value = []
  }
  queryParam.value = {
    locationArea: customerName.value.join('/'),
    registerDateMin: e.registDate ? `${formatDate(e.registDate[0], 'YYYY-MM-DD')}` : null,
    registerDateMax: e.registDate ? `${formatDate(e.registDate[1], 'YYYY-MM-DD')}` : null,
    ...e,
  }
  delete queryParam.value.registDate
  getList()
}

function handleUpdateSubmit() {
  console.log(updateFormModel.value.remark, 'remark', updateFormModel.value.zlagencyId)
  if (updateFormModel.value.remark && updateFormModel.value.zlagencyId) {
    zlAgencyService.update(updateFormModel.value)
      .then((response) => {
        console.log('修改成功')
        Message.success('修改成功')
        updateDialogVisible.value = false
        getList()
      })
      .finally(() => {

      })
  }
  else {
    console.log('修改失败')
    updateDialogVisible.value = false
  }
}

function handleReset() {
  updateDialogVisible.value = false
  updateDialogTitle.value = '修改备注'
}

// function handleDelete(row) {
//   let customerID
//   if (row) {
//     customerID = row.customerId
//   }
//   else {
//     customerID = ids.value.join(',')
//   }
//   zlAgency.delete(customerID).then((res) => {
//     const { code } = res
//     if (code === 200) {
//       Message.success('删除成功')
//       getList()
//     }
//   })
// }

function handleFormAction(row, type) {
  ElMessageBox.prompt('', '修改备注', {
    inputValue: row.remark,
    inputPattern: /^[\s\S]*$/,
    inputErrorMessage: '备注不能为空',
    inputType: 'textarea',
    inputPlaceholder: '请输入备注',
  }).then(({ value }) => {
    const params = {
      ...row,
      remark: value,
    }
    zlAgencyService.update(params)
      .then((response) => {
        if (response.code == 200) {
          Message.success('修改备注成功')
          getList()
        }
      })
      .catch((err) => {

      })
  })
}

function handleExport() {
  proxy.download('system/customerInformation/export', { ...queryParam.value, exportIds: ids.value.join(',') }, `user_${new Date().getTime()}.xlsx`)
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <SearchBar
        :search-config="searchConfig"
        @search="handleSearch"
      />
    </el-card>
    <el-card shadow="never">
      <div class="toolbar flex mb-1">
        <div class="mb-2 space-x-3">
          <el-button v-hasPermi="['system:finance:zlAgency:export']" type="warning" class="el-gradient-warning" @click="handleExport()">
            导出
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
        </div>
        <RightToolbar />
      </div>
      <vxe-grid
        :data="tableData"
        :columns="tableColumns"
        :pager-config="pagerConfig"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellClass"
        :loading="btnLoad"
        max-height="580px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #skNode="{ row }">
          <dict-tag
            :options="sys_proceeds_time"
            :value="row.skNode"
          />
        </template>
        <template #status="{ row }">
          <dict-tag
            :options="sys_pay_status"
            :value="row.status"
          />
        </template>
        <template #operate="{ row }">
          <el-button
            v-hasPermi="['system:finance:zlAgency:edit']" text type="success" size="small"
            @click="handleFormAction(row, 'edit')"
          >
            修改备注
          </el-button>
        </template>
      </vxe-grid>
    </el-card>
    <el-dialog
      v-model="updateDialogVisible"
      :destroy-on-close="true"
      class="custom-dialog"
      width="500px"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px] ">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="updateFormList"
        :model="updateFormModel"
        class="px-5"
        :options="{ disabled: formDisabled }"
        @submit="handleUpdateSubmit"
        @cancel="handleReset"
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.dialog-header{
  width: 180px;
  height: 0;
  border-width: 0px 45px 45px 0px;
  border-style: none solid solid;
  border-color: transparent transparent var(--el-color-primary);
  color: #fff;
  display: flex;
  justify-content: center;
}
</style>
